package com.neo.rabbitmq.four;

import com.neo.rabbitmq.utils.RabbitMqUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: ConfirmMessage
 * @Title: rabbitmq-demo
 * @Package: com.neo.rabbitmq.four
 * @Description: 发布确认模式
 * 使用的时间 比较哪种确认方式是最好的
 * 1、单个确认
 * 2、批量确认
 * 3、异步确认
 * @Author: Kisen
 * @Date: 2021/9/7 22:59
 */
public class ConfirmMessage {

    // 批量发送消息个数
    public static final int MESSAGE_COUNT = 1000;

    // 单个确认
    public static void publishMessageIndividually() throws IOException, TimeoutException, InterruptedException {
        Channel channel = RabbitMqUtil.getChannel();
        // 队列的声明
        String queueName = UUID.randomUUID().toString().replace("-", "");
        channel.queueDeclare(queueName, true, false, false, null);
        // 开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis(); // 开始时间
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes());
            // 单个消息发布确认
            boolean flag = channel.waitForConfirms();
            if (flag) {
                System.out.println("消息发送成功");
            }
        }
        long end = System.currentTimeMillis(); // 结束时间
        // 发布1000个单独确认消息，耗时647ms
        System.out.println(String.format("发布%d个单独确认消息，耗时%dms", MESSAGE_COUNT, end - begin));
    }

    // 批量确认
    public static void publishMessageBatch() throws IOException, TimeoutException, InterruptedException {
        Channel channel = RabbitMqUtil.getChannel();
        // 队列的声明
        String queueName = UUID.randomUUID().toString().replace("-", "");
        channel.queueDeclare(queueName, true, false, false, null);
        // 开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis(); // 开始时间

        // 批量确认消息大小
        int batchSize = 100;
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes());
            // 每100条批量确认一次
            if (i % batchSize == 0) {
                // 发布确认
                channel.waitForConfirms();
            }
        }

        long end = System.currentTimeMillis(); // 结束时间
        // 发布1000个批量确认消息，耗时68ms
        System.out.println(String.format("发布%d个批量确认消息，耗时%dms", MESSAGE_COUNT, end - begin));
    }

    // 异步确认
    public static void publishMessageAsync() throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        // 队列的声明
        String queueName = UUID.randomUUID().toString().replace("-", "");
        channel.queueDeclare(queueName, true, false, false, null);
        // 开启发布确认
        channel.confirmSelect();

        /**
         * 线程安全有序的一个哈希表 适用高并发的情况下
         * 1.轻松的将序号与消息进行关联
         * 2.轻松批量删除条目 只要给到序号
         * 3.支持高并发（多线程）
         */
        ConcurrentSkipListMap<Long, String> outstandingConfirms = new ConcurrentSkipListMap<>();

        /**
         * 消息确认成功 回调函数
         *  1.消息的标记
         *  2.是否为批量确认
         */
        ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
            // 2:删除掉已经确认的消息 剩下的就是未确认的消息
            if (multiple) {
                ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliveryTag);
                confirmed.clear();
            } else {
                outstandingConfirms.remove(deliveryTag);
            }
            System.out.println("确认的消息：" + deliveryTag);
        };
        // 消息确认失败 回调函数
        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            // 3:打印一下未确认的消息都有哪些
            String message = outstandingConfirms.get(deliveryTag);
            System.out.println("未确认的消息是：" + message + ", 未确认的消息tag：" + deliveryTag);
        };
        /**
         * 准备消息的监听器
         *  1.监听哪些消息成功了
         *  2.监听哪些消息失败了
         */
        channel.addConfirmListener(ackCallback, nackCallback);

        long begin = System.currentTimeMillis(); // 开始时间
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = "消息" + i;
            channel.basicPublish("", queueName, null, message.getBytes());
            // 1:记录下所有要发送的消息 消息的总和
            outstandingConfirms.put(channel.getNextPublishSeqNo(), message);
        }

        long end = System.currentTimeMillis(); // 结束时间
        // 发布1000个异步确认消息，耗时38ms
        System.out.println(String.format("发布%d个异步确认消息，耗时%dms", MESSAGE_COUNT, end - begin));
    }


    public static void main(String[] args) throws InterruptedException, TimeoutException, IOException {
        // 1、单个确认
        //ConfirmMessage.publishMessageIndividually();
        // 2、批量确认
        //ConfirmMessage.publishMessageBatch();
        // 3、异步确认
        ConfirmMessage.publishMessageAsync();
    }
}
